init = ->
    DeviceWidth = window.document.body.clientWidth

    cnv = document.getElementById('demoCanvas')
    cnv.style.width = if window.document.body.clientWidth < 400 then window.document.body.clientWidth + 'px' else 400 + 'px'
    stage = new createjs.Stage(cnv)
    createjs.Touch.enable(stage)
    r = new GameBox(stage)
    stage.canvas.width = stage.canvas.height = DeviceWidth * 2

    r.initial()

#    createjs.Ticker.timingMode = createjs.Ticker.RAF;
    createjs.Ticker.setFPS(30);
    createjs.Ticker.addEventListener('tick',stage)

    window.stage = stage
    window.gameBox = r

    document.getElementById('now_num').innerText = '4'
    document.getElementById('aim_num').innerText = '11'
    xhr({
#        url:'http://192.168.1.6:8080/getJsSign'
        url:'https://wingsfrog.com/irons/access_token.php?jsapi=1&href='+ location.href.replace('&','%26')
        method:'POST'
        data:{
            "uniacid":"3"
        }
        success: (data) ->
            data = JSON.parse(data)
            jsConfig('wx1af3d7165f94ed69',data.timestamp,data.noncestr,data.sign)
    })
jsConfig = (js_appId, js_timestamp, js_nonceStr, js_signature) ->
        wx.config({
                    debug: false,
                    appId: js_appId,
                    timestamp: js_timestamp,
                    nonceStr: js_nonceStr,
                    signature: js_signature,
                    jsApiList: ['chooseWXPay','onMenuShareTimeline','onMenuShareAppMessage','onMenuShareQQ','onMenuShareWeibo','scanQRCode']
                }
        )
        wx.ready(
            ->
                jsShare('我发现了一款好玩的小游戏，看看谁能先得到数字11吧:-P','https://wingsfrog.com/g/','','')
        )

shareToOther = ->
    jsShare('我费尽我所有智商,终于得到'+window.gameBox.maxNum+'了,你们能超越我吗?','https://wingsfrog.com/g/','http://wingsfrog.com/g/img/'+window.gameBox.maxNum+'.png','')
    document.getElementById('share-cover').style.display='block'

jsShare = (title, link, imgUrl, desc, type='link', dataUrl = '') ->
        wx.onMenuShareTimeline({
                    title: title
                    link: link
                    imgUrl: imgUrl
                    success: ->
                    cancel: ->
                }
        )

        wx.onMenuShareAppMessage({
                    title: title, # 分享标题
                    desc: desc, # 分享描述
                    link: link, # 分享链接
                    imgUrl: imgUrl, # 分享图标
                    type: type, # 分享类型,music、video或link，不填默认为link
                    dataUrl: dataUrl, # 如果type是music或video，则要提供数据链接，默认为空
                    success: ->
                    cancel: ->
                }
        )

        wx.onMenuShareQQ({
                    title: title, # 分享标题
                    desc: desc, # 分享描述
                    link: link, # 分享链接
                    imgUrl: imgUrl, # 分享图标
                    success: ->
                    cancel: ->
                }
        )

        wx.onMenuShareWeibo({
                    title: title, # 分享标题
                    desc: desc, # 分享描述
                    link: link, # 分享链接
                    imgUrl: imgUrl, # 分享图标
                    success: ->
                    cancel: ->
                }
        )


replay = ->
    document.getElementById('now_num').innerText = '4'
    document.getElementById('aim_num').innerText = '11'
    window.stage.removeAllChildren()
    window.gameBox.reset()
    cancel()

cancel = ->
    cover = document.getElementById('cover-box')
    win_box = document.getElementById('win-box')
    win_box.style.display = 'none'
    cover.style.display = 'none'
    back_cover = document.getElementById('back-cover')
    back_cover.style.display = 'none'

GameBox = (stage) ->
    this.gameBox = [
           [0,0,0,0,0],
           [0,0,0,0,0],
           [0,0,0,0,0],
           [0,0,0,0,0],
           [0,0,0,0,0]
        ]
    this.maxNum = 4
    this.score  = 0
    this.stage = stage
    this.reset = () ->
        this.gameBox = [
            [0,0,0,0,0],
            [0,0,0,0,0],
            [0,0,0,0,0],
            [0,0,0,0,0],
            [0,0,0,0,0]
        ]
        this.maxNum = 4
        this.score  = 0
        this.initial()

    this.initial = () ->
        self = this
        for i in [1..5]
            for j in [1..5]
                if this.gameBox[i-1][j-1] == 0
                    fillNum = Math.floor(Math.random() * this.maxNum)

                    this.gameBox[i-1][j-1] = new RectSprite(fillNum,i,0)
                    this.gameBox[i-1][j-1].down(this.stage,j)
                    box = this.gameBox[i-1][j-1]
                    box.drawSelf(this.stage)

                    ((i,j,box,self)->
                        box.rect.addEventListener('click',(e) ->
                                e.box = box
                                e.father = self
                                check(e)
                        )
                    )(i,j,box,self)

        this.checkend()
        return

    #页面动画悲观锁定
    queue = 0
    this.increase = (x,y) ->
        destoryList = this.recuse(x,y)
        queue = 0
        for item in destoryList
            queue++
            this.gameBox[item.x][item.y].destroy(this.stage,x+1,y+1,this)
            this.gameBox[item.x][item.y]=0

        this.gameBox[x][y].gather(this.stage)
        if this.gameBox[x][y].num + 1 > this.maxNum
            this.maxNum++
            document.getElementById('now_num').innerText = this.maxNum
            jsShare('我费尽我所有智商,终于得到'+window.gameBox.maxNum+'了,你们能超越我吗?','https://wingsfrog.com/g/','http://wingsfrog.com/g/img/'+window.gameBox.maxNum+'.png','')
            if this.maxNum == 11
                cover = document.getElementById('win-box')
                cover.style.display = 'block'
                back_cover = document.getElementById('back-cover')
                back_cover.style.display = 'block'
                document.getElementById('aim_num').innerText = 12
            else if this.maxNum == 12
                cover = document.getElementById('win-box')
                cover.style.display = 'block'
                back_cover = document.getElementById('back-cover')
                back_cover.style.display = 'block'
                document.getElementById('aim_num').innerText = 15
            else if this.maxNum == 15
                cover = document.getElementById('win-box')
                cover.style.display = 'block'
                back_cover = document.getElementById('back-cover')
                back_cover.style.display = 'block'
                document.getElementById('aim_num').innerText = 20
            else if this.maxNum == 20
                cover = document.getElementById('win-box')
                cover.style.display = 'block'
                back_cover = document.getElementById('back-cover')
                back_cover.style.display = 'block'
                document.getElementById('aim_num').innerText = 25

    this.update = () ->
        if(--queue==0)
            for i in [5..1]
                y_boxs = []#记录为0的位置,非0的顺序填下来
                for j in [5..1]
                    if this.gameBox[i-1][j-1] == 0
                        y_boxs.push {"y":j}
                        continue
                    else
                        if y_boxs.length > 0
                            y = y_boxs[0].y
                            this.gameBox[i-1][j-1].down(this.stage,y)
                            this.gameBox[i-1][y-1] = this.gameBox[i-1][j-1]
                            this.gameBox[i-1][j-1] = 0
                            y_boxs = y_boxs.slice(1)
                            y_boxs.push {"y":j}

            this.initial()

    this.boxDown = () ->

    this.drawself = () ->
        for i in [1..5]
            for j in [1..5]
                this.gameBox[i-1][j-1].drawSelf(this.stage)

    check = (e) ->
        gb = e.father
        n = e.box.num
        x = e.box.x - 1
        y = e.box.y - 1
        if (x-1 < 0 or gb.gameBox[x-1][y].num!=n ) and (x+1 > 4 or gb.gameBox[x+1][y].num!=n )and
                ( y-1 <0 or gb.gameBox[x][y-1].num!=n )and (y+1 >4 or gb.gameBox[x][y+1].num!=n )
            createjs.Tween.get(e.box.rect, { loop: false })
                .to({ scaleY: 0.8 }, 100, createjs.Ease.getPowInOut(2))
                .to({ scaleY: 1 }, 100, createjs.Ease.getPowInOut(4))
            return
        gb.increase(x,y)


    this.recuse = (x,y) ->
        archive_stash = []
        aim_stash = [{'x':x,'y':y}]

        isrecuse = (x,y) ->
                for v in archive_stash
                    if v.x == x and v.y == y
                        return true
                for v in aim_stash
                    if v.x == x and v.y == y
                        return true
                false

        (aim_x = aim_stash[0].x
        aim_y = aim_stash[0].y
        aim = this.gameBox[aim_x][aim_y]
        if aim_x-1 > -1 and
                aim.num == this.gameBox[aim_x-1][aim_y].num and
                !isrecuse(aim_x-1,aim_y)
            aim_stash.push({x:aim_x-1,y:aim_y})

        if aim_x+1 < 5 and
                aim.num == this.gameBox[aim_x+1][aim_y].num and
                !isrecuse(aim_x+1,aim_y)
            aim_stash.push({x:aim_x+1,y:aim_y})

        if aim_y-1 > -1 and
                aim.num == this.gameBox[aim_x][aim_y-1].num and
                !isrecuse(aim_x,aim_y-1)
            aim_stash.push({x:aim_x,y:aim_y-1})

        if aim_y+1 < 5 and
                aim.num == this.gameBox[aim_x][aim_y+1].num and
                !isrecuse(aim_x,aim_y+1)
            aim_stash.push({x:aim_x,y:aim_y+1})

        archive_stash.push(aim_stash[0])
        aim_stash = aim_stash.slice(1)
        )until(aim_stash.length==0)
        archive_stash = archive_stash.slice(1)
        return archive_stash

    this.checkend = ->
        for i in [1..5]
            for j in [1..5]
                aim_x = i - 1
                aim_y = j - 1
                aim = this.gameBox[aim_x][aim_y]
                if aim_x-1 > -1 and
                        aim.num == this.gameBox[aim_x-1][aim_y].num
                    return false

                if aim_x+1 < 5 and
                        aim.num == this.gameBox[aim_x+1][aim_y].num
                    return false

                if aim_y-1 > -1 and
                        aim.num == this.gameBox[aim_x][aim_y-1].num
                    return false
                if aim_y+1 < 5 and
                        aim.num == this.gameBox[aim_x][aim_y+1].num
                    return false
        cover = document.getElementById('cover-box')
        cover.style.display = 'block'
        back_cover = document.getElementById('back-cover')
        back_cover.style.display = 'block'
        jsShare('我费尽我所有智商,终于得到'+window.gameBox.maxNum+'了,你们能超越我吗?','https://wingsfrog.com/g/','http://wingsfrog.com/g/img/'+window.gameBox.maxNum+'.png','')
    return


RectSprite = (num,x,y) ->
    this.num = num
    this.x = x
    this.y = y
    this.rect = new createjs.Container()
    this.padding = 5
    this.white = 5
    colors = [
        '551984','ED752B','009E9D','E5005A','FCCB00','74934F','AE3E91','00A0E8','0068B2','C60022'
        'AF61A3','E4007E','F39700','ED752B','EE93AE','EA5404','2E8E6B','68392A','21AB38','F9D0C9'
    ]

    this.getColors = ->
        '#' + colors[this.num]

    this.drawSelf = (stage) ->
        this.rect.removeAllChildren()

        drawSize = this.calculateSize(stage.canvas.width)
        W = this.calculateX(drawSize)
        H = this.calculateY(drawSize)
        this.rect.x = W
        this.rect.y = H

        box = new createjs.Shape()
        box.graphics.clear()
        box.graphics.beginFill(this.getColors()).drawRoundRect(0,0,drawSize,drawSize,5)
        txt = new createjs.Text(this.num+1, "72px Arial", "#EDEDED")
        txt.x = (drawSize - txt.getMeasuredWidth())/2
        txt.y = (drawSize - txt.getMeasuredHeight())/2 - 2
        this.rect.addChild(box,txt)
        stage.addChild(this.rect)

    this.calculateSize = (width) ->
        (width - 2 * this.padding) / 5 - 2 * this.white

    this.calculateX = (drawSize) ->
        this.padding + (this.x - 1) * (drawSize +  this.white) + this.x * this.white

    this.calculateY = (drawSize) ->
        this.padding + (this.y - 1) * (drawSize +  this.white) + this.y * this.white

    this.gather = (stage) ->
        self = this
        callback = ->
            self.drawSelf(stage)
        this.num++
        createjs.Tween.get(this.rect, { loop: false })
            .to({ scaleX: 1.2,scaleY:1.2 }, 200, createjs.Ease.getPowInOut(4))
            .call(callback)
            .to({ scaleX: 1,scaleY:1 }, 200, createjs.Ease.getPowInOut(2))

    this.destroy = (stage , x ,y , newRs) ->
        callback = ->
            newRs.update(stage)
        drawSize = this.calculateSize(stage.canvas.width)
        createjs.Tween.get(this.rect, { loop: false })
            .to({ alpha: 0,x:this.padding + (x - 1) * (drawSize +  this.white) + x * this.white ,y:this.padding + (y - 1) * (drawSize +  this.white) + y * this.white }, 200, createjs.Ease.getPowInOut(2))
            .call(callback)

    this.down = (stage,y) ->
        this.y = y
        drawSize = this.calculateSize(stage.canvas.width)
        createjs.Tween.get(this.rect, { loop: false })
        .to({y:this.padding + (y - 1) * (drawSize +  this.white) + y * this.white }, 200, createjs.Ease.getPowInOut(2))
    return






